<script setup>
import { ref, onMounted, computed } from 'vue'
import {getOrderList, deliverOrder, rejectRefund, approveRefund} from '@/api/user'
import { ElMessage } from 'element-plus'

const orders = ref([])

const loadOrders = async () => {
  const res = await getOrderList()
  orders.value = res.data
}

const statusPriority = {
  4: 0, // 退款审核中
  1: 1, // 待发货
  2: 2, // 待收货
  3: 3, // 已完成
  0: 4, // 已取消
  5: 5, // 已退款
  6: 6  // 退款被拒绝
}

const sortedOrders = computed(() => {
  return [...orders.value].sort((a, b) => {
    const pA = statusPriority[a.status] ?? 99
    const pB = statusPriority[b.status] ?? 99
    if (pA !== pB) return pA - pB
    return new Date(b.createTime) - new Date(a.createTime)
  })
})


const handleDeliver = async (orderId) => {
  const res = await deliverOrder(orderId)
  if (res.code === 0) {
    ElMessage.success('发货成功')
    await loadOrders()
  } else {
    ElMessage.error(res.message || '发货失败')
  }
}

onMounted(() => {
  loadOrders()
})

const formatOrderStatus = (status) => {
  switch (status) {
    case 0: return '已取消'
    case 1: return '待发货'
    case 2: return '待收货'
    case 3: return '已完成'
    case 4: return '退款审核中'
    case 5: return '已退款'
    case 6: return '退款被拒绝'
    default: return '未知状态'
  }
}

// 获取行样式
const getRowStyle = ({ row }) => {
  switch (row.status) {
    case 1: // 待发货
      return { background: 'rgba(255, 229, 143, 0.1)' }
    case 2: // 待收货
      return { background: 'rgba(143, 201, 255, 0.1)' }
    case 3: // 已完成
      return { background: 'rgba(183, 235, 143, 0.1)' }
    case 0: // 已取消
      return { background: 'rgba(238, 238, 238, 0.5)' }
    case 4:
      return { background: 'rgba(255, 153, 0, 0.1)' }   // 退款审核中
    case 5:
      return { background: 'rgba(64, 158, 255, 0.1)' }   // 已退款
    case 6:
      return { background: 'rgba(255, 0, 0, 0.05)' }     // 被拒
    default:
      return {}
  }
}

const approveRefundHandler = async (id) => {
  const res = await approveRefund(id)
  if (res.code === 0) {
    ElMessage.success('已同意退款')
    loadOrders()
  } else {
    ElMessage.error(res.message)
  }
}

const rejectRefundHandler = async (id) => {
  const res = await rejectRefund(id)
  if (res.code === 0) {
    ElMessage.success('已拒绝退款')
    loadOrders()
  } else {
    ElMessage.error(res.message)
  }
}

const activeStatus = ref(null) // null 表示全部

const filteredOrders = computed(() => {
  if (activeStatus.value === null) return sortedOrders.value
  return sortedOrders.value.filter(order => order.status === activeStatus.value)
})

</script>

<template>
  <el-card>
    <template #header>
      <div class="header">
        <span style="font-size: 18px; font-weight: bold">订单管理</span>
      </div>
    </template>
    <el-button-group style="margin-bottom: 20px">
      <el-button :type="activeStatus === null ? 'primary' : 'default'" @click="activeStatus = null">全部</el-button>
      <el-button :type="activeStatus === 4 ? 'primary' : 'default'" @click="activeStatus = 4">退款审核中</el-button>
      <el-button :type="activeStatus === 2 ? 'primary' : 'default'" @click="activeStatus = 2">待收货</el-button>
      <el-button :type="activeStatus === 1 ? 'primary' : 'default'" @click="activeStatus = 1">待发货</el-button>
      <el-button :type="activeStatus === 3 ? 'primary' : 'default'" @click="activeStatus = 3">已完成</el-button>
      <el-button :type="activeStatus === 0 ? 'primary' : 'default'" @click="activeStatus = 0">已取消</el-button>
      <el-button :type="activeStatus === 5 ? 'primary' : 'default'" @click="activeStatus = 5">已退款</el-button>
      <el-button :type="activeStatus === 6 ? 'primary' : 'default'" @click="activeStatus = 6">退款被拒绝</el-button>
    </el-button-group>
    <el-table
        :data="filteredOrders"
        style="width: 100%"
        :row-style="getRowStyle"
        border
        stripe
    >
      <el-table-column prop="id" label="订单ID" width="60px" align="center" />
      <el-table-column prop="orderNo" label="订单编号"  />
      <el-table-column prop="username" label="用户名"  />
      <el-table-column prop="mobile" label="手机号"  />
      <el-table-column label="商品" >
        <template #default="{ row }">
          <div class="product-names">
            {{ row.productNames }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额"  align="right">
        <template #default="{ row }">
          ¥{{ row.totalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentAmount" label="实付金额"  align="right">
        <template #default="{ row }">
          <span style="color: #f56c6c; font-weight: bold">
            ¥{{ row.paymentAmount.toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" >
        <template #default="{ row }">
          <el-tag
              :type="row.status === 1 ? 'warning' :
                   row.status === 2 ? 'primary' :
                   row.status === 3 ? 'success' : 'info'"
              size="small"
              effect="light"
          >
            {{ formatOrderStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180px" />
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <!-- 退款审核操作 -->
            <template v-if="scope.row.status === 4">
              <div class="button-group-vertical">
                <div class="button-container">
                  <el-button type="success" size="small" class="op-button" @click="approveRefundHandler(scope.row.id)">
                    同意退款
                  </el-button>
                </div>
                <div class="button-container">
                  <el-button type="danger" size="small" class="op-button" @click="rejectRefundHandler(scope.row.id)">
                    拒绝退款
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 发货操作 -->
            <el-button
                v-else-if="scope.row.status === 1"
                type="primary"
                size="small"
                class="op-button"
                @click="handleDeliver(scope.row.id)"
            >发货</el-button>

            <!-- 已发货 -->
            <el-button
                v-else-if="scope.row.status === 2"
                type="success"
                size="small"
                disabled
                class="op-button"
            >已发货</el-button>

            <!-- 其他状态 -->
            <el-text v-else type="info">无需操作</el-text>
          </div>
        </template>
      </el-table-column>

    </el-table>
  </el-card>
</template>

<style scoped>

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-names {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}

/* 为表格添加悬停效果 */
:deep(.el-table__body tr:hover>td) {
  background-color: rgba(64, 158, 255, 0.08) !important;
}

/* 调整表格单元格内边距 */
:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell) {
  padding: 8px 0;
}

.button-container {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: flex-start; /* 左对齐 */
  gap: 6px; /* 按钮间距 */
}

.op-button {
  min-width: 80px;
  white-space: nowrap;
}

.button-group-vertical {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 垂直间距 */
}

</style>
